package com.snails.app;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;

import com.snails.app.configuration.IConfiguration;
import com.snails.app.configuration.model.SnailsDebug;
import com.snails.app.configuration.model.SnailsNetwork;
import com.snails.app.utils.DiskLruCacheUtil;
import com.snails.app.utils.StorageSingleton;
import com.snails.logger.Logger;
import com.snails.logger.LoggerConfig;
import com.snails.net.SnailsNet;
import com.snails.tool.app.ActivityStackManager;
import com.snails.tool.clipboard.ClipboardUtil;
import com.snails.tool.display.DisplayUtils;

/**
 * app快速框架
 *
 * @author lawrence
 * @date 2019-04-02  18:41:36
 * <p>
 * 使用：
 * 1、需先调用SnailsApp.instance().init()初始化
 */

public class SnailsApp {
    private static volatile SnailsApp instance = null;
    private Context ctx = null;
    private IConfiguration iConfiguration = null;

    public static SnailsApp instance() {
        if (instance == null) {
            synchronized (SnailsApp.class) {
                if (instance == null)
                    instance = new SnailsApp();
            }
        }
        return instance;
    }

    // ================================================================================
    // --- ---
    // ================================================================================
    /**
     * 初始化SnailsApp陪住
     * @param application   application
     * @param configuration app配置
     */
    public void init(Application application, IConfiguration configuration) {
        checkInit(application, configuration);
        initial(this.ctx = application.getApplicationContext());
        setDebugConfiguration(iConfiguration = configuration);
        DiskLruCacheUtil.setVersion(iConfiguration.diskLruCacheVersion());
        SnailsNet.instance().init(this.ctx, getBaseUrl(iConfiguration), iConfiguration);
        application.registerActivityLifecycleCallbacks(callbacks);
    }

    public Context getCtx() {
        return ctx;
    }

    public IConfiguration configuration() {
        return iConfiguration;
    }

    // 是否测试环境
    public boolean isTest() {
        if (iConfiguration != null
                && iConfiguration.network() != null) {
            if (iConfiguration.network().isOnline()) {
                return true;
            }
            return !StorageSingleton.instance().getBoolean("online", false);
        }
        return true;
    }

    // 设置当前环境状态
    public void setTest(boolean isTest) {
        if (iConfiguration != null
                && iConfiguration.network() != null
                && !iConfiguration.network().isOnline()) {
            StorageSingleton singleton = StorageSingleton.instance();
            singleton.putBoolean("online", !isTest).commit();
        }
    }

    // ================================================================================
    // --- ---
    // ================================================================================
    // 检查参数有效性
    private void checkInit(Application application, IConfiguration configuration) {
        if (application == null) {
            throw new NullPointerException("application 不能为 null");
        }
        if (configuration == null) {
            throw new NullPointerException("configuration 不能为 null");
        } else if (configuration.debug() == null) {
            throw new NullPointerException("configuration中debug未设置");
        } else if (configuration.network() == null) {
            throw new NullPointerException("configuration中network未设置");
        }
    }

    // ================================================================================
    // --- ---
    // ================================================================================
    private SnailsApp() { }

    // 对需要Context的数据初始化
    private void initial(Context ctx) {
        DisplayUtils.init(ctx);         // 初始化屏幕信息
        ClipboardUtil.initCtx(ctx);     // 初始化剪贴板的Context
    }

    // activity生命周期回调
    private Application.ActivityLifecycleCallbacks
            callbacks = new Application.ActivityLifecycleCallbacks() {
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            ActivityStackManager.instance().add(activity);
        }
        @Override
        public void onActivityStarted(Activity activity) { }
        @Override
        public void onActivityResumed(Activity activity) { }
        @Override
        public void onActivityPaused(Activity activity) { }
        @Override
        public void onActivityStopped(Activity activity) { }
        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) { }
        @Override
        public void onActivityDestroyed(Activity activity) {
            ActivityStackManager.instance().remove(activity);
        }
    };

    // 设置debug的配置
    private void setDebugConfiguration(IConfiguration configuration) {
        if (configuration != null && configuration.debug() != null) {
            SnailsDebug snails = configuration.debug();
            final LoggerConfig config = Logger.init();
            config.setTag(snails.tag).setDebug(snails.debug)
                    .setThreadInfo(snails.threadInfo).setFormat(snails.format);
            Logger.i("日志已开启：tag=%s thread=%b format=%b",
                    snails.tag, snails.threadInfo, snails.format);
        }
    }

    // 得到baseUrl
    private String getBaseUrl(IConfiguration configuration) {
        if (configuration != null && configuration.network() != null) {
            final SnailsNetwork network = configuration.network();
            if (network != null) {
                if (network.isOnline()) {
                    return network.productUrl();
                }
                return isTest() ? network.testUrl : network.productUrl();
            }
        }
        return null;
    }

}
